import os.path
import util.common as common
from flask import Flask, render_template, request, url_for, redirect, jsonify
from werkzeug.utils import secure_filename
import logging
from pypinyin import pinyin, lazy_pinyin

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello World!'


@app.route('/api/file/list', methods=['GET', 'POST'])
def file_list():
    file_list = common.query_cur_file()
    return jsonify(file_list)


@app.route('/index', methods=['GET', 'POST'])
def index():
    name = 'zhqngsas'
    return render_template('index.html', name=name)


@app.route('/upload', methods=['GET', 'POST'])
def upload():
    return render_template('upload.html')


@app.route('/api/upload', methods=['GET', 'POST'])
def api_upload():
    data = {

    }
    if request.method == 'POST':
        f = request.files['txt_file']
        filesname = "".join(lazy_pinyin(f.filename))
        # 当前的文件所在路劲
        basepath = os.path.dirname(__file__)
        upload_path = os.path.join(basepath, 'static/uploads', secure_filename(filesname))
        f.save(upload_path)
        return jsonify(data)
    return render_template('upload.html')


if __name__ == '__main__':
    handler = logging.FileHandler('flask.log', encoding='UTF-8')  # 设置日志字符集和存储路径名字
    logging_format = logging.Formatter(  # 设置日志格式
        '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')
    handler.setFormatter(logging_format)
    app.logger.addHandler(handler)
    app.config['JSON_AS_ASCII'] = False
    app.debug = True
    app.run()
